package dao

import (
	"context"
	"github.com/ego-component/egorm"
	"gorm.io/gorm/clause"
	"time"
)

type AsyncTask struct {
	ID        int64  `gorm:"primaryKey;autoIncrement;comment:主键"`
	TaskID    string `gorm:"type:varchar(255);uniqueIndex:idx_task_id;comment:任务id"`
	AsyncReq  string // 请求
	Status    int32  `gorm:"type:int;comment:任务状态 0-未处理 1-处理中 2-成功 3-失败 4-取消"`
	AsyncResp string // 响应
	Ctime     int64  `gorm:"column:ctime;comment:创建时间戳（毫秒）"`
	Utime     int64  `gorm:"column:utime;comment:更新时间戳（毫秒）"`
}

type AsyncTaskDAO interface {
	Save(ctx context.Context, task AsyncTask) error
	GetTaskByID(ctx context.Context, taskId string) (AsyncTask, error)
}

type asyncRepo struct {
	db *egorm.Component
}

func NewAsyncTaskDAO(db *egorm.Component) AsyncTaskDAO {
	return &asyncRepo{
		db: db,
	}
}

func (a *asyncRepo) Save(ctx context.Context, task AsyncTask) error {
	now := time.Now().Unix()
	task.Ctime = now
	task.Utime = now
	return a.db.WithContext(ctx).Debug().
		Model(&AsyncTask{}).Clauses(
		clause.OnConflict{
			Columns: []clause.Column{
				{
					Name: "task_id",
				},
			},
			DoUpdates: clause.AssignmentColumns([]string{"status", "async_resp", "utime"}),
		},
	).Create(&task).Error
}

func (a *asyncRepo) GetTaskByID(ctx context.Context, taskId string) (AsyncTask, error) {
	var task AsyncTask
	err := a.db.WithContext(ctx).
		Where("task_id = ?", taskId).Scan(&task).Error
	return task, err
}
